const https = require('https')
const fs = require('fs');
const rl = require("readline");
const axios = require('axios');
const xlsUtils = require('./xlsUtils');


let xls = [];
const CodeMap = {
    '移动': '移动',
    '联通': '联通',
    '电信': '电信'
}

// const reader = rl.createInterface({ input: fs.createReadStream("./failnumbers.txt") });
// reader.on("line", mobile => {
//
// });


//     hostname: 'xhzw.market.alicloudapi.com',
//     method: 'POST',
//     headers: {
//         'Authorization':'APPCODE 0959a450496a45fe825a755b1e5f3da4'
//     }
// }
const options = {
    url: 'https://xhzw.market.alicloudapi.com/isp',
    method: "POST",
    headers: {'Authorization': 'APPCODE 0959a450496a45fe825a755b1e5f3da4'},
}
//
fs.readFile("./failnumbers.txt", "utf8", async (err, data) => {
    data = data.split("\r\n")
    for (let mobile of data) {
        console.log(mobile);
        if (mobile.length === 0) {
            continue;
        } else {
            options.params = {mobile: mobile}
        }
        try {
            const response = await axios(options)
            console.log(response.data);
            if (response.data.code != 0) {
                console.log(response.data);
            } else {
                let result = response.data.result;
                // if (result.Init_isp != result.Now_isp) {
                    result.Init_isp_code = CodeMap[result.Init_isp],
                    result.Now_isp_code = CodeMap[result.Now_isp]
                    xls.push(result)
                // }
            }

        } catch (error) {
            console.log(error);
        }
    }

    let buffer = xlsUtils.buildExcelResultBuf([{
        sheet: 'sheet1',
        title: [{
            name: '手机号码',
            key: 'Mobile'
        }, {
            name: '归属地',
            key: 'Area'
        }, {
            name: '转网前运营商',
            key: 'Init_isp_code'
        }, {
            name: '转网后运营商',
            key: 'Now_isp_code'
        }],
        data : xls
    }]);

    fs.writeFileSync('./mobiles.xlsx', buffer);
    console.log('文档以输出，请查阅。');
});

//
// const data = JSON.stringify({
//     mobile: '13001529183'
// })
//
// const options = {
//     hostname: 'xhzw.market.alicloudapi.com',
//     path: '/isp?mobile=' + '13001595828',
//     method: 'POST',
//     headers: {
//         'Authorization':'APPCODE 0959a450496a45fe825a755b1e5f3da4'
//     }
// }
//
// const req = https.request(options, res => {
//     console.log(`状态码: ${res.statusCode}`)
//
//     res.on('data', d => {
//         process.stdout.write(d)
//     })
// })
//
// req.on('error', error => {
//     console.error(error)
// })
//
// req.write(data)
// req.end()
// curl -i -k -X POST 'https://xhzw.market.alicloudapi.com/isp?mobile=13001529183'  -H 'Authorization:APPCODE 0959a450496a45fe825a755b1e5f3da4' -H 'Content-Type:application/json; charset=UTF-8'
